import json
import elu.backyard.parameter.model as Model

from elu.base.handler import BaseHandler


class ParameterHandler(BaseHandler):
    def get(self):
        self.render("backyard/manage/parameter.html")

    def post(self):
        raw = json.loads(self.request.body.decode('utf-8'))


class ParameterPersonnelAPIHandler(BaseHandler):
    def get(self):
        table = Model.ParameterModel('supp_personnel')
        results = table.r()
        self.write(json.dumps(results))

    def post(self):
        workno = self.parse_argument('workno')
        name = self.parse_argument('name')
        domain = self.parse_argument('domain')
        position = self.parse_argument('position')

        table = Model.ParameterPersonnelModel()
        recruit = table.c(workno, name, domain, position)
        self.write(json.dumps(recruit))

    def delete(self):
        data = self.parse_argument('id')
        table = Model.ParameterPersonnelModel()
        dismiss = table.d(data)

        if dismiss == 'success':
            self.write(json.dumps('success'))
        else:
            self.write(json.dumps('fail'))


class ParameterAPIHandler(BaseHandler):
    def initialize(self, tablename):
        self.tablename = tablename

    def get(self):
        table = Model.ParameterModel(self.tablename)
        results = table.r()
        self.write(json.dumps(results))

    def post(self):
        data = self.parse_argument('name')
        table = Model.ParameterModel(self.tablename)
        recruit = table.c(data)

        if recruit == 'success':
            # Send callback to Backbone to re-render
            self.write(json.dumps(data))
        elif recruit == 'duplicate':
            self.write(json.dumps('duplicate'))
        else:
            self.write(json.dumps('fail'))

    def delete(self):
        data = self.parse_argument('id')
        table = Model.ParameterModel(self.tablename)
        dismiss = table.d(data)

        if dismiss == 'success':
            self.write(json.dumps('success'))
        else:
            self.write(json.dumps('fail'))